package com.david.core.utils

import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast

/**
 * 使用时先调用： ToastUtils.instance.init(applicationContext)初始化
 * */
class ToastUtils {
    private lateinit var view: FrameLayout
    private lateinit var tv: TextView
    private var toast: Toast? = null

    companion object{
        var instance:ToastUtils = ToastUtils()
    }

    /**
     * 初始化Toast
     * @param context
     */
    fun init(context: Context?) {
        if (context == null) {
            throw Exception("context for init must not be null")
            return
        }
        view = FrameLayout(context)
        view.layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
        tv = TextView(context)
        tv.textSize = 16f
        tv.setTextColor(Color.parseColor("#3e3a39"))
        view.addView(tv)
        toast = Toast(context)
        toast!!.view = view

        toast?.setGravity(Gravity.CENTER, 0, 0)

    }

    /**
     * 显示Toast
     * @param content 内容
     * @param duration Toast持续时间
     */
    private fun display(content: CharSequence, duration: Int) {
        if (content.isNotEmpty()) {
            tv.text = content
            toast?.duration = duration
            toast?.show()
            Log.e("char", content.toString() + "  " + (toast == null))
        }
    }


    /**
     * 显示toast
     * @param content  内容
     * @param duration  持续时间
     */
    fun toast(content: String?, duration: Int) {
        if (content != null) {
            display(content, duration)
        }

    }

    /**
     * 显示默认持续时间为short的Toast
     * @param content  内容
     */
    fun toast(content: String?) {
        toast(content, Toast.LENGTH_SHORT)
    }

    fun isInited():Boolean{
        return this::tv.isInitialized
    }
}